<script lang="ts" setup>
import type { AiPromptTemplatesApi } from '#/api/ai/prompt/promptTemplates';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import Template from '../info/template.vue';

const formData = ref<AiPromptTemplatesApi.PromptTemplates>();
const templateRef = ref<InstanceType<typeof Template>>();
const loading = ref(false);
const currentStep = ref(0);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    const data = drawerApi.getData<AiPromptTemplatesApi.PromptTemplates>();
    if (!data) {
      return;
    }
    formData.value = data;
  },
});
/** 下一步 */
function nextStep() {
  templateRef.value?.nextStep();
  currentStep.value = templateRef.value?.currentStep || 0;
}

/** 上一步 */
function prevStep() {
  templateRef.value?.prevStep();
  currentStep.value = templateRef.value?.currentStep || 0;
}
/** 提交表单 */
async function submitForm() {
  // 表单验证
  loading.value = true;
  try {
    await templateRef.value?.submitForm();
  } finally {
    loading.value = false;
  }
}
/** 步骤改变 */
function onStepChange(index: number) {
  currentStep.value = index;
}
/** 成功 */
function onSuccess() {
  drawerApi.close();
}
</script>

<template>
  <Drawer
    title="创建提示词"
    class="w-[90%]"
    :closable="false"
    :show-cancel-button="false"
    :show-confirm-button="false"
  >
    <template #extra>
      <div class="mt-4 flex justify-end space-x-2">
        <Button :disabled="currentStep === 0" @click="prevStep">上一步</Button>
        <Button :disabled="currentStep === 5" @click="nextStep">
          下一步
        </Button>
        <Button type="primary" :loading="loading" @click="submitForm">
          保存
        </Button>
      </div>
    </template>
    <Template
      ref="templateRef"
      :template="formData"
      :hidden-btn="true"
      class="mx-4"
      @change="onStepChange"
      @success="onSuccess"
    />
  </Drawer>
</template>
